package com.kdl.webconfig.controller;


import com.kdl.webconfig.entity.User;
import com.kdl.webconfig.service.IUserService;
import com.kdl.webconfig.utils.JWTUtils;
import com.kdl.webconfig.vo.BaseRespVO;
import com.kdl.webconfig.vo.config.LoginRespVO;
import com.kdl.webconfig.vo.config.LoginUserVO;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

@RestController
public class LoginController {

    @Resource
    private IUserService iUserService;

    @PostMapping("/login")
    public BaseRespVO<LoginRespVO> login(@RequestBody LoginUserVO loginUser) {
//        String code = loginUser.getCode();
//        String uuid = loginUser.getUuid();
//        if (StringUtils.isEmpty(loginUser.getCode()) && StringUtils.isEmpty(loginUser.getUuid())) {
//            //删除验证码
//            redisUtil.delete(uuid);
//            throw new RuntimeException("验证码不能为空！");
//        }
//        //验证验证码
//        if (!verifyCode(code, uuid)) {
//            //删除验证码
//            redisUtil.delete(uuid);
//            throw new RuntimeException("验证码不正确，请重新输入！");
//        }
//        //查询登录对象
        User user = iUserService.selectByUserName(loginUser.getUserName());
        if (Objects.isNull(user)) {
            //删除验证码
//            redisUtil.delete(uuid);
            throw new RuntimeException("登录用户不存在");
        }
//        //判断密码
        if (!verifyPassword(loginUser.getPwd(), user.getPassword())) {
            //删除验证码
//            redisUtil.delete(uuid);
            throw new RuntimeException("对不起，您的账号密码不正确，请重新输入");
        }
        LoginRespVO loginRespVO = new LoginRespVO();
//        //生成token
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userId",user.getId().toString());
        hashMap.put("userName",user.getUserName());
        String token = JWTUtils.getToken(hashMap,3*60*60);
//        //返回token
        loginRespVO.setToken(token);
        return BaseRespVO.success(loginRespVO);
    }

   

    /**
     * 获取验证码
     *
     * @return
     */
//    @GetMapping("/getCode")
//    public AjaxResult getCode() {
//        HashMap<String, String> number = getVerificationCode.getNumber();
//        number.forEach((k, v) -> {
//            redisUtil.set(k, v, Constant.CODE_DETE);
//        });
//        return AjaxResult.success(number);
//    }

    /**
     * 判断密码是否一致
     *
     * @param value1 前端传入的值
     * @param value2 数据库查询的值
     * @return
     */
    public boolean verifyPassword(String value1, String value2) {
        if (value1.equals(value2)) {
            return true;
        } else {
            return false;
        }
    }


}
